<?php
add_filter('the_content', 'wptexturize');
add_filter('the_content', 'convert_chars');
add_filter('the_content', 'wpautop');

if (!defined('PERPAGE')) {
    define('PERPAGE', 15);
}

require_once('template_parse.php');

# 获取当前url目录
function url_get($key) {
    global $params;
    if (isset($params[$key])) {
        return $params[$key];
    }
    return null;
} 

# 获取网站Title
function site_title() {
    echo get_option('site_title');
}

# 获取网站描述
function site_description() {
    echo get_option('site_description');
}

# 获取站点url
function site_url() {
    global $aldb;
    echo $aldb->get_var("SELECT `option_value` FROM $aldb->options WHERE `option_name`='site_url'");
}

# 获取站点主页url
function home_url() {
    global $aldb;
    echo $aldb->get_var("SELECT `option_value` FROM $aldb->options WHERE `option_name`='home_url'");
}

# 获取站点email
function site_email() {
    echo get_option('site_email');
}

# get diagram parent list

function get_diagram_parent_list_by_child($id = '') {
    global $aldb;
    if (!empty($id)) {
        $parent_list[] = $id;
    } else {
        $parent_list = array();
    }
    $parent_id = $aldb->get_var("SELECT `parent` FROM $aldb->diagram WHERE `id`='$id'");
    if (!empty($parent_id)) {
        $parent_list  = array_merge($parent_list, get_diagram_parent_list_by_child($parent_id));
    }
    return $parent_list;
}

/*
根据url或者id还要类型获取Diagram
如果没有的话,就自动使用THIS_URL获取
*/

function get_diagram_by_url($url = '', $type = '', $fields = array()) {
    global $aldb;
    if (empty($fileds)) {
        $fields = '*';
    }
    if (empty($url)) {
        $url = THIS_URL;
    }
    $id = (int)$url;
    if (empty($id) || $id != $url) {
        $condition = "url='$url'";
    } else {
        $condition = "id='$id'";
    }
    if (!empty($type)) {
        $condition .= " AND `type`='$type'";
    } else {
        $condition .= '';
    }
    return $aldb->get_row("SELECT $fields FROM $aldb->diagram WHERE $condition LIMIT 1");
}

# get the diagram childs
function get_diagram_childs_by_id($id) {
    global $aldb;
    return $results = $aldb->get_results("SELECT * FROM $aldb->diagram WHERE parent='$id' ORDER BY displayorder ASC");
}

# get the diagram childs by url
function get_diagram_childs_by_url($url = '') {
    global $aldb;
    $diagram = get_diagram_by_url($url);
    if (!empty($diagram)) {
        return get_diagram_childs_by_id($diagram->id);
    }
}

# get the diagram childs list
function get_diagram_childs_list_by_id($id) {
    $childs = get_diagram_childs_by_id($id);
    $childs_list = '';
    foreach($childs as $child) {
        $childs_list .= $child->id . ',';
    }
    $childs_list = trim($childs_list, ',');
    return $childs_list;
}

# get he diagram childs list by slug
function get_diagram_childs_list_by_url($slug) {
    $diagram = get_diagram_by_url($slug);
    return get_diagram_childs_list_by_id($diagram->id);
}


# is_exists_slug
function is_exists_url($slug) {
    $diagram = get_diagram_by_url($slug);
    if (empty($diagram) || empty($diagram->id)) {
        return false;
    } else {
        return true;
    }
}

# get the diagram content
function diagram_content($slug) {
    echo _diagram_content($slug);
}

function _diagram_content($slug) {
    global $aldb,$html;
    $diagram = $aldb->get_row("SELECT `content`, `id` FROM `$aldb->diagram` WHERE `slug`='$slug' AND `type`='page' LIMIT 1");
    if (!empty($diagram)) {
        $content = $diagram->content;
        # check is is admin
        $current_user = current_user();
        if (!empty($current_user->id)) {
            $content .= '<p>' . $html->admin_link('编辑', "/diagram/page_edit/$diagram->id/edit_from_web/?" . THIS_URL, array('style'=>'color:#ff0000;')) . '</p>';
        }
    } else {
        $content = '';
    }
    return $content;
}



# get the current diagram submenu list
function get_sub_menu_list($current_diagram) {
    global $html, $diagram_cache, $init;

    if (isset($diagram_cache[$current_diagram->id])) {
        $count = count($diagram_cache[$current_diagram->id]);
        $li = false;
        $ul = false;
        for($i = 0; $i < $count; $i++) {
            $diagram_sub = $diagram_cache[$current_diagram->id][$i];
            if ($i == 0 && $init['indentation']) {
                echo '<ul>',"\n";
                $ul = true;
            }

            $li_class = '';
            $url = $diagram_sub->url;
            if (THIS_URL == $diagram_sub->url) {
                $li_class = 'class="' . $init['li_selected_class'] . '"';
            } else {
                
            }
            if ($diagram_sub->type == 'item') {
                $a = $diagram_sub->title;
                $li_class = 'class="' . $init['item_class'] . '"';
            } else {
                $a = $html->link($diagram_sub->title, $url);
            }
            echo '<li ',$li_class,'>',$a,'</li>',"\n";
            echo get_sub_menu_list($diagram_sub);

            if ($li) {
                echo '</li>';
            } else if ($ul && $init['indentation'] && $i == ($count -1)) {
                echo '</ul>';
            }
        }
    }
}

# get the diagram_root by slug
function get_diagram_root_by_url($url) {
    global $aldb;
    $diagram = $aldb->get_row("SELECT * FROM $aldb->diagram WHERE url='$url' LIMIT 1");
    if ($diagram->parent != 0) {
        return get_diagram_root_by_id($diagram->parent);
    } else {
        return $diagram;
    }
}

# get the diagram root by id
function get_diagram_root_by_id($diagram_id) {
    global $aldb;
    $diagram = $aldb->get_row("SELECT * FROM $aldb->diagram WHERE id='$diagram_id' LIMIT 1");
    if (!empty($diagram) && $diagram->parent != 0) {
        return get_diagram_root_by_id($diagram->parent);
    } else {
        return $diagram;
    }
}

function get_diagram_by_id($id) {
    global $aldb;
    return $aldb->get_row("SELECT * FROM $aldb->diagram WHERE id='$id'");
}

function get_list() {
    echo _get_list();
}


function _get_list($category = '') {
    if (empty($category)) {
        $category = get_diagram_by_url('', 'list');
    }
    $list_type = get_diagram_metavalue('list_type', $category->metavalue);

    $output = '';
    $parameter = array('category'=>$category, 'category_id'=>$category->id);
    switch($list_type) {
        case 'images':
            $output .= _get_images_list($parameter);
            break;
        default:
        case 'news':
            $output .= _get_news_list($parameter);
            break;
    }
    return $output;
}



function get_news_list($settings = array()) {
    echo _get_news_list($settings);
}

/*
目前效率非常低,不好,需要用Cache来改进,但是赶时间,暂时这样
*/
function _get_news_list($settings = array()) {
    global $html;
    $posts = get_posts($settings);
    $output = "<ul>\n";
    if (!empty($settings['category'])) {
        $category = $settings['category'];
    }
    foreach($posts as $post) {
        if (empty($category)) {
            $category = get_category_by_post($post->id);
        }
        $output .= '<li>' . $html->link($post->post_title,  get_post_url($category->url,$post)) . ' <span class="post_time">' . time_format($post->post_time) . '</span></li>';
    }
    $output .= "</ul>\n";
    return $output;
}

function get_images_list($settings = array()) {
    echo _get_images_list($settings);
}

function _get_images_list($settings = array()) {
    global $html;
    $posts = get_posts($settings);
    if (!empty($settings['category'])) {
        $category = $settings['category'];
    }
    $output = "<div class=\"image_list\">\n";
    foreach($posts as $post) {
        $link = get_post_url($category->url,$post);
        $output .= '<div class="image_item">';
        $output .= '<div class="image_item_image">' . $html->link('<img src="' . thumbnail_url($post->id, 1) . '" class="img"/>', $link) . '</div>';
        $output .= '<div class="image_item_title">' . $html->link($post->post_title, $link) . '</div>';
        $output .= '</div>';
    }
    $output .= "</div>\n";
    return $output;
}

function get_posts($settings = array()) {
    global $aldb;
    $default_params = array('url'=>null, 'limit'=>0, 'star'=>false, 'category_id'=>0, 'perpage'=>'', 'childs'=>true);
    $settings += $default_params;
    if (empty($settings['perpage'])) {
        $perpage = PERPAGE;
    }

    if (empty($settings['url'])) {
        $settings['url'] = THIS_URL;
    }
    if (empty($settings['category_id']) && !empty($settings['url'])) {
        if ($settings['childs']) {
            $type = '';
        } else {
            $type = 'list';
        }
        $diagram = get_diagram_by_url($settings['url'], $type);
        $settings['category_id'] = !empty($diagram) ? $diagram->id : 0;
    }
    arlicle_components('diagram');
    if ($settings['childs']) {
        $category_list = cache_diagram_childs($settings['category_id']);
    } else {
        $category_list = '';
    }
    if (empty($category_list)) {
        $category_list = $settings['category_id'];
        $condition = "c.category_id='$category_list'";
    } else {
        $category_list .= $settings['category_id'];
        $condition = "c.category_id IN ($category_list) ";
    }
    if ($settings['star']) {
        $condition .= " AND star_status='1'";
    }
    if (empty($settings['limit'])) {
        $page = params(2);

        if (empty($page)) {
            $page = 1;
        }
        $count = $aldb->get_var("SELECT COUNT(p.id) FROM $aldb->post2category as c LEFT JOIN $aldb->posts as p ON c.post_id=p.id WHERE $condition");

        $total_page = ceil($count/$perpage);
        $GLOBALS['total_page'] = $total_page;
        if ($page < 1) {
            $page = 1;
        } else if ($page > $total_page) {
            $page = $total_page;
        }
        $start = ($page -1) * $perpage;
        $limit_sql = "LIMIT $start,$perpage";
    } else {
        $limit_sql = "LIMIT $settings[limit]";
    }
    $results = $aldb->get_results("SELECT p.* FROM $aldb->post2category as c LEFT JOIN $aldb->posts as p ON c.post_id=p.id WHERE $condition ORDER BY p.post_time DESC $limit_sql");
    return $results;    
}

/*
获取加星的post
*/
function get_star_posts($settings = array()) {
    $settings['star'] = true;
    return get_posts($settings);
}

function next_page($title) {
    echo get_pagelink_simple($title, 1);
}

function prev_page($title) {
    echo get_pagelink_simple($title, -1);
}

function get_pagelink_simple($title, $page) {
    global $html, $total_page;
    $link = true;
    $current_page = (int)params(2);
    if ($current_page < 1) {
        $current_page = 1;
    }
    $page_id = $current_page + $page;

    if ($page_id < 1) {
        $page_id = 1;
        if ($page > 0) {
            $page_id += 1;
        } else {
            $link = false;
        }
    } else if ($page_id > $total_page) {
        $page_id = $total_page;
        if ($page < 0) {
            $page_id -= 1;
        } else {
            $link = false;
        }
    }

    if ($link) {
        $link = THIS_URL . "page/$page_id/";
    } else {
        $title = null;
    }
    return $html->link($title, $link);
}

function post_title($id = null) {
    global $aldb;
    echo _post_title($id);
}

function _post_title($id = null) {
    global $aldb;
    if (empty($id)) {
        $id = params(2);
    }
    $post = get_post($id);
    if (!empty($post)) {
        return $post->post_title;
    }
}

function _post_content($id = null) {
    global $aldb;
    $id = (int)$id;
    $content = $aldb->get_var("SELECT post_content FROM $aldb->posts WHERE id='$id'");
    if (!empty($content)) {
        return $content;
    }
}

function post_content($id = null) {
    echo _post_content($id);
}

function thumbnail_url($post_id, $size = 0) {
    global $aldb;
    $thumbnail = $aldb->get_row("SELECT * FROM $aldb->attachments WHERE post_id='$post_id' AND is_thumbnail='1'");
    $image_path = '';
    if (!empty($thumbnail)) {
        $file_path = Router::get_base() . 'www/attach/' . date('Y/n/j/', $thumbnail->upload_time) . $thumbnail->upload_time;
        $file_ab_path =  ROOT . 'www/attach/' . date('Y/n/j/', $thumbnail->upload_time) . $thumbnail->upload_time;
        if (!empty($size) && file_exists("{$file_ab_path}_{$size}.$thumbnail->extra")) {
            $image_path = "{$file_path}_{$size}.$thumbnail->extra";
        } else {
            $image_path = "{$file_path}.$thumbnail->extra";
        }
    }
    return $image_path;
}

# 获取自定义字段的值
function meta_value($post_id, $key) {
    global $aldb;
    return $aldb->get_var("SELECT meta_value FROM $aldb->customvalues WHERE post_id='$post_id' AND meta_key='$key'");
}

/*
通过post_id 或者post_slug来取得category
*/
function get_category_by_post($slug='') {
    global $aldb;
    $id = (int)$slug;
    if ($id != $slug) {
        $condition = "p.post_slug='$slug'";
    } else {
        $condition = "p.id='$id'";
    }
    return $aldb->get_row("SELECT d.* FROM $aldb->diagram as d LEFT JOIN $aldb->post2category as p ON d.id=p.category_id WHERE $condition");
}

function get_post($slug) {
    global $aldb;
    $id = (int)$slug;

    if ($slug != $id . '') {
        $slug = urldecode($slug);
        $condition = "post_slug='$slug'";
    } else {
        $condition = "id='$id'";
    }

    return $aldb->get_row("SELECT * FROM $aldb->posts WHERE $condition LIMIT 1");
}

function al_paginate($settings = array()) {
    global $total_page;
    if (empty($settings['perpage'])) {
        $settings['perpage'] = PERPAGE;
    }
    if (empty($settings['paginate_style'])) {
        $settings['paginate_style'] = 'paginate_1';
    }
    return call_user_func($settings['paginate_style'], params(2), $total_page, $settings['perpage'], THIS_URL . 'page/');
}

function paginate_1($current_page, $total, $limit, $base = '') {
    global $html;
    if (empty($total)) {
        return '';
    }
    $lastp = $total;
    $thisp = (int)$current_page;
    if ($thisp < 1) {
        $thisp = 1;
    } else if ($thisp > $total) {
        $thisp = $total;
    }
    $offset = ($thisp -1) * $limit + 1;

    $output = "<div class=\"paginator\">\n";
    if ($thisp==1) {
        $output .= '<span class=\"disabled\">' . __('&lt; Prev') . '</span>';
    } else {
        $output .= $html->link(__('&lt; Prev'), $base . ($thisp -1) . '/', array('class'=>'prev'));
    }
    $page1 = $base . "1";
    $page2 = $base . ($limit + 1);

    if ($thisp <= 8) {
        for ($p = 1; $p <= min( ($thisp<=3) ? 5 : $thisp+2,$lastp); $p++) {
            if ($p == $thisp) {
                $output .= "      <span class=\"current\">$p</span>\n ";
            } else {
                $output .= ' ' . $html->link($p, $base . $p . '/');
            }
        }

        if ($lastp > $p) {
            $output .= "      <span class=\"break\">...</span>\n";
        }
    } else if ($thisp > 8) {
        $output .= " <span class=\"break\">...</span>\n ";
        for ($p = $thisp - 3; $p <= (($lastp-$thisp<= 6) ? $lastp : $thisp + 3); $p++) {
            if ($p == $thisp) {
                $output .= "      <span class=\"this-page\">$p</span>\n ";
            } else if ($p <=$lastp) {
                $output .= ' ' . $html->link($p, $base . $p . '/');
            }
        }
        if ($lastp > $p+1) {
            $output .= "      <span class=\"break\">...</span>\n";
        }
    }

    if ($thisp == $lastp) { 
        $output .= '      <span class=\"disabled\"> ' . __('Next &gt;') . '</span> ';
    } else {
        $output .= ' ' . $html->link(__('Next &gt;'), $base . ($thisp + 1) . '/', array('class'=>'next')) . ' ';
    }
        $output .=  "</div>\n";
        return $output;
}
?>
